extends Node2D

@onready var players: Node2D = $Players
@onready var enemies: Node2D = $Enemies
@onready var startup : Node2D = get_node("/root/Startup")


func _ready() -> void:
	if not multiplayer.is_server():
		return
	
	multiplayer.peer_connected.connect(add_player)
	multiplayer.peer_disconnected.connect(del_player)
	add_player(1)


func add_player(id: int) -> void:
	var player_test := preload("res://demo/multi/player_test.tscn").instantiate()
	player_test.peer_id = id
	var pos := Vector2(randi_range(100, 1200), randi_range(100, 1000))
	player_test.global_position = pos
	player_test.name = str(id)
	players.add_child(player_test, true)



func del_player(id: int) -> void:
	if players.has_node(str(id)):
		players.get_node(str(id)).queue_free()


func _exit_tree() -> void:
	if not multiplayer.is_server():
		return
	multiplayer.peer_connected.disconnect(add_player)
	multiplayer.peer_disconnected.disconnect(del_player)


func _on_timer_timeout() -> void:
	if multiplayer.is_server():
		var pos := Vector2(randi_range(100, 800), randi_range(100, 600))
		new_bad(pos)



@rpc("any_peer", "call_local")
func new_board() -> void:
	var inst := preload("res://demo/multi/board.tscn").instantiate()
	get_node("/root/Startup/LevelBox/World").add_child(inst)


func _on_bad_man_dead() -> void:
	new_board.rpc()


func new_bad(pos: Vector2) -> void:
	var bad_man_tcsn := preload("res://demo/multi/bad_man.tscn")
	var newOb := bad_man_tcsn.instantiate()
	newOb.tree_exited.connect(_on_bad_man_dead)
	newOb.global_position = pos
	enemies.add_child(newOb, true)
